<?php
include_once("../../../untils/conn.php"); // 引入数据库连接配置文件

// 获取用户输入的手机号和IP地址
$phoneNumber = $_POST["phoneNumber"];
$ipAddress = $_SERVER['REMOTE_ADDR'];
$sutime = time();
$id = '1';
$sql = "SELECT * FROM sms WHERE id =" . $id;
$result = mysqli_query($con, $sql);

if ($result->num_rows > 0) {
    // 输出数据
    while ($row = $result->fetch_assoc()) {
        // 获取每个字段的值
        $appId = $row["appid"];
        $appKey = $row["appkey"];
        $templateId = $row["te_ids"];
        $smsSign = $row["sign"];
    }

    // 生成6位随机数字作为验证码
    $verificationCode = mt_rand(100000, 999999);

    // 将验证码和IP地址存储起来
    $sql = "INSERT INTO vercodes (phone, code, ip , sutime) VALUES ('$phoneNumber', '$verificationCode', '$ipAddress' , '$sutime')";
    mysqli_query($con, $sql);

    // 发送短信验证码
    $params = array(
        '{1}' => $verificationCode,
    );

    $currentTimeStamp = time();
    $random = rand(1000000, 9999999);

    $requestParms = array(
        'tel' => array(
            'nationcode' => '86',
            'mobile' => $phoneNumber,
        ),
        'sig' => hash("sha256", "appkey=$appKey&random=$random&time=$currentTimeStamp&mobile=$phoneNumber", false),
        'tpl_id' => $templateId,
        'params' => array_values($params),
        'sign' => $smsSign,
        'time' => $currentTimeStamp,
        'extend' => '',
        'ext' => ''
    );

    $requestJson = json_encode($requestParms);

    $url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid=$appId&random=$random";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $requestJson);
    $response = curl_exec($ch);
    curl_close($ch);

    $responseData = json_decode($response, true);

    if ($responseData["result"] == 0) {
        // 发送成功
        $jsonResponse = array("code" => 200, "msg" => "验证码发送成功");
    } else {
        // 发送失败
        $jsonResponse = array("code" => 400, "msg" => "验证码发送失败");
        // $jsonResponse = array("code" => 400, "msg" => "验证码发送失败！失败原因：" . $responseData["errmsg"]);
    }
} else {
    // 未找到匹配的记录
    $jsonResponse = array("code" => 400, "msg" => "未找到匹配的记录");
}

// 返回JSON响应
echo json_encode($jsonResponse);
?>
